//
//  QINetworkManager.swift
//  SameCity
//
//  Created by 秦江涛 on 2023/6/1.
//

import UIKit
import RxSwift
import Alamofire
import SwiftyUserDefaults

class QINetworkManager: NSObject {
    
    //completionHandler: ((AFDataResponse<Data?>) -> Void)? = nil
    //completionHandler: dataBlock? = nil
    /// 返回data
    /// - Parameters:
    class func request(urlStr: String, method: HTTPMethod = .post, parameters: Parameters?, success: @escaping dataBlock) {
        
        let token = Defaults[\.token]
        let headers: HTTPHeaders = [
            "Authorization": token
        ]
        print(token)
        AF.request("\(BASE_URL)\(urlStr)", method: method, parameters: parameters, headers: headers).response { res in
            switch res.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
                print(json)
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                guard model.code == 200 else {
                    if model.msg.count > 0 {
                        ShowHUD(str: model.msg)
                    }
                    return
                }
                let dataJsonStr = "\(json["data"])"
                let testData = dataJsonStr.data(using: .utf8) ?? Data()
                success(testData)
            case let .failure(err):
                ShowHUD(str: "\(urlStr)调用出错")
                print(err)
            }
        }
    }
    
    /// 返回json
    /// - Parameters:
    class func requestJson(urlStr: String, method: HTTPMethod = .post, parameters: Parameters?, success: @escaping jsonBlock, fail: @escaping jsonBlock) {
        
        let bearer = Defaults[\.bearer]
        let headers: HTTPHeaders = [
            "Authorization": bearer
        ]
        var urlString = ""
        if urlStr.contains("://") {
            urlString = urlStr
        } else {
            urlString = "\(BASE_URL)\(urlStr)"
        }
        print("------------URL-------------")
        print(urlStr)
//        print(headers)
        print(parameters ?? [:])
        print("------------URL-------------")
        AF.request(urlString, method: method, parameters: parameters, headers: headers).response { res in
            if res.response != nil {
                let header:[String: Any] = res.response?.allHeaderFields as! [String : Any]
                let authorizationStr = "\(header["Authorization"] ?? "")"
                if authorizationStr.count > 0 {
                    print("---------authorizationSt=\(authorizationStr)")
                    Defaults[\.bearer] = authorizationStr
                }
            }
            
            
            switch res.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
//                print(json)
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                guard model.code == 1 else {
                    ShowHUD(str: model.msg)
                    print(model.msg)
                    fail(json)
                    return
                }
                success(json["data"])
            case let .failure(err):
                fail(JSON())
                ShowHUD(str: "\(urlStr)调用出错")
                print(err)
            }
        }
    }
    
    
    class func requestJson(urlStr: String, method: HTTPMethod = .post, parameters: Parameters?, isJson: Bool = false, success: @escaping jsonBlock) {
        let bearer = Defaults[\.bearer]
        let headers: HTTPHeaders = [
            "Authorization": bearer
        ]
        var urlString = ""
        if urlStr.contains("://") {
            urlString = urlStr
        } else {
            urlString = "\(BASE_URL)\(urlStr)"
        }
        print("------------URL-------------")
        print(urlString)
        print("------------URL-------------")
//        print("------------headers-------------")
//        print(headers)
//        print("------------headers-------------")
        print("------------parameters-------------")
        print(parameters ?? [:])
        print("------------parameters-------------")
        AF.request(urlString, method: method, parameters: parameters, encoding: isJson ? JSONEncoding.default : URLEncoding.default, headers: headers).response { res in
            if res.response != nil {
                let header:[String: Any] = res.response?.allHeaderFields as! [String : Any]
                let authorizationStr = "\(header["Authorization"] ?? "")"
                if authorizationStr.count > 0 {
                    print("---------authorizationSt=\(authorizationStr)")
                    Defaults[\.bearer] = authorizationStr
                }
            }
            
            HUD.hide()
            
            
            switch res.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
//                print(json)
                
                // 客户的接口使用json请求,且没有返回code值
                if isJson {
                    success(json)
                    return
                }
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                if model.code == 1 {
                    success(json["data"])
                } else if model.code == 401 {   //登录
                    ShowHUD(str: model.msg)
                    Defaults[\.isLogin] = false
                    let window = UIApplication.shared.keyWindow
                    window?.switchRootCtrl()
                } else if model.code == 106 || model.code == 107 {
                    let window = UIApplication.shared.keyWindow
                    
                    let ctl = QuestionnaireSurveyViewController()
                    ctl.code = model.code
                    window?.rootViewController?.navigationController?.pushViewController(ctl, animated: true)
                } else if model.code == 0 {
                    ShowHUD(str: model.msg)
                    printLog(model.msg)
                }
                
            case let .failure(err):
                ShowHUD(str: "\(urlString)调用出错")
                print(err)
            }
        }
    }
    
    /// 返回任意类型的model
    /// - Parameters:
    class func requestModel<T: Convertible>(urlStr: String, method: HTTPMethod = .post, parameters: Parameters?, modeType: T.Type, success: @escaping (_ model: T)->()) {
        let token = Defaults[\.token]
        let headers: HTTPHeaders = [
            "Authorization": token
        ]
        let urlStr = "\(BASE_URL)\(urlStr)"
        AF.request(urlStr, method: method, parameters: parameters, headers: headers).response { res in
            print("------------URL-------------")
            print(urlStr)
            print(parameters ?? [:])
            print("------------URL-------------")
            
            switch res.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
                print(json)
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                guard model.code == 200 else {
                    ShowHUD(str: model.msg)
                    return
                }
                let tModel = json["data"].dictionaryObject?.kj.model(modeType) ?? T()
                success(tModel )
            case let .failure(err):
                ShowHUD(str: "\(urlStr)调用出错")
                print(err)
            }
        }
    }
    
    
    /// 返回任意类型的model数组
    /// - Parameters:
    class func requestModelArr<T: Convertible>(urlStr: String, method: HTTPMethod = .post, parameters: Parameters?, modeType: T.Type, success: @escaping (_ modelArr: [T])->()) {
        let token = Defaults[\.token]
        let headers: HTTPHeaders = [
            "Authorization": token
        ]
        let urlStr = "\(BASE_URL)\(urlStr)"
        print("------------URL-------------")
        print(urlStr)
        print("------------URL-------------")
        AF.request(urlStr, method: method, parameters: parameters, headers: headers).response { res in
            switch res.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
                print(json)
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                guard model.code == 200 else {
                    ShowHUD(str: model.msg)
                    return
                }
                let modelArr = json["data"].arrayObject?.kj.modelArray(T.self) ?? [T]()
                success(modelArr)
            case let .failure(err):
                ShowHUD(str: "\(urlStr)调用出错")
                print(err)
            }
        }
    }
    
    
    class func requestWithModel<T: Convertible>(urlStr: String, method: HTTPMethod = .post, parameters: Parameters?, model: T.Type) -> Single<T> {
        
        return Single<T>.create { signal in
            let token = Defaults[\.token]
            let headers: HTTPHeaders = [
                "Authorization": token
            ]
            print(token)
            AF.request("\(BASE_URL)\(urlStr)", method: method, parameters: parameters, headers: headers).response { res in
                switch res.result {
                case let .success(data):
                    guard data != nil else {
                        ShowHUD(str: "返回数据为空")
                        return
                    }
                    
                    let json = JSON(data!)
                    print(json)
                    let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                    guard model.code == 200 else {
                        ShowHUD(str: model.msg)
                        return
                    }
                    let tModel = json["data"].dictionaryObject?.kj.model(T.self) ?? T()
                    signal(.success(tModel))
                case let .failure(err):
                    ShowHUD(str: "\(urlStr)调用出错")
                    print(err)
                    signal(.failure(err))
                }
            }
            
            return Disposables.create()
        }
        
    }
    
    
    class func uploadImage(urlStr: String, image: UIImage, success: @escaping dictionaryBlock) {
        
        let data = image.jpegData(compressionQuality: 1) ?? Data()
        let newImg = UIImage(data: data)
//        let urlStr = "https://1207admin.62.dianchuiguan.com.cn/api/common/upload"
        let urlStr = "\(IMAGE_URL)/api/common/upload"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let dateString = formatter.string(from: Date())
        let fileName = "iOS-\(dateString).jpeg"
        
        AF.upload(multipartFormData: { multipartFormData in
            
            /**
             1. data 要上传文件的二进制
             2. name 是服务器定义的字段名称 - 后台接口文档会提示
             3. fileName 是保存在服务器的文件名，但是：现在通常可以随便写，后台会做一些处理
             - 根据上传的文件，生成 缩略图，中等图，高清图
             - 保存在不同路径，并且自动生成文件名
             - fileName 是 HTTP 协议定义的属性
             
             4. mimeType  / contentType: 客户端通知服务器，二进制数据的准确类型
             - 大类型 / 小类型
             * image/gif  image/jpg image/png
             * text/plain text/html
             * application/json
             - 服务器不准确的类型
             * application/octet-stream
             */
            
            multipartFormData.append(data, withName: "file", fileName: fileName, mimeType: "image/jpeg")
            
        }, to: urlStr)
        .uploadProgress { progress in
            print("---------\(progress.fractionCompleted)")
        }
        .response { resp in
            switch resp.result {
            case let .success(data):
                guard data != nil else {
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
                print(json)
                let model = json.dictionaryObject?.kj.model(QIDictBaseModel.self) ?? QIDictBaseModel()
                guard model.code == 1 else {
                    ShowHUD(str: model.msg)
                    return
                }
                success(model.data)
            case let .failure(err):
                ShowHUD(str: "\(urlStr)调用出错")
                print(err)
            }
        }
        
    }
    
    
    
    
    class func uploadImageDetection(urlStr: String, image: UIImage, success: @escaping jsonBlock, fail: @escaping jsonBlock) {

        let bearer = Defaults[\.bearer]
        let headers: HTTPHeaders = [
            "Authorization": bearer
        ]
        print(headers)
        
        
        let data = image.jpegData(compressionQuality: 1) ?? Data()//image.pngData() ?? Data()//
        let newImg = UIImage(data: data)
        let urlStr = "\(DetectionIMAGE_URL)\(urlStr)"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMddHHmmss"
        let dateString = formatter.string(from: Date())
        let fileName = "iOS-\(dateString).jpeg"
        
        print(urlStr)
        AF.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(data, withName: "image", fileName: fileName, mimeType: "image/jpeg")
        }, to: urlStr, headers: headers)
        .uploadProgress { progress in
            print("---------\(progress.fractionCompleted)")
        }
        .response { resp in
            switch resp.result {
            case let .success(data):
                guard data != nil else {
                    fail(JSON())
                    ShowHUD(str: "返回数据为空")
                    return
                }
                
                let json = JSON(data!)
                print(json)
                success(json)
            case let .failure(err):
                ShowHUD(str: "\(urlStr)调用出错")
                print(err)
                fail(JSON())
            }
        }
        
    }
    
    
    /// 获取网络权限
    class func getNetworkPermissions () {
        // 构建URL
        let url:URL = URL(string: "\(BASE_URL)/Index/project")!
        // 发送HTTP请求的的session对象
        let session = URLSession.shared
        // 构建请求request
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        // 发一个get请求
        let task = session.dataTask(with: request as URLRequest) {(
            data, response, error) in
            
            guard let data = data, let _:URLResponse = response, error == nil else {
                print("error")
                return
            }
            let dataString =  String(data: data, encoding: String.Encoding.utf8)
            
            print(dataString ?? "")
        }
        task.resume()
        
    }
        
}

